package com.guoxue.action.back;



import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.guoxue.domain.BackUserVo;
import com.guoxue.service.IBackUsersService;
import com.guoxue.service.IChapterConfigService;
import com.guoxue.service.IRecordConfigService;
import com.guoxue.service.IUserService;
import com.guoxue.util.ErrorCodeUtil;
import com.guoxue.util.ErrorMsgUtil;
import com.guoxue.util.LoggerUtil;
import com.guoxue.util.OtherUtils;
import com.guoxue.util.PagePathUtil;
import com.guoxue.util.PasswordUtil;
/***
 * @author zhangpeng
 * @date 2016-07-13 16:15:00
 */
@Controller
@RequestMapping(value="/back")
public class LoginLogoutAction {
	
	@Resource
	private IUserService userService;
	@Resource
	private IChapterConfigService chapterConfigDaoService;
	@Resource
	private IRecordConfigService recordConfigDaoService;
	@Resource
	private IBackUsersService backUsersService;
	
	public static void writeFile(String filePath, String sets)  
            throws IOException {  
        FileWriter fw = new FileWriter(filePath);  
        PrintWriter out = new PrintWriter(fw);  
        out.write(sets);  
        out.println();  
        fw.close();  
        out.close();  
    }  
	
	/***
	 * @return 
	 */
	@RequestMapping(value="/index")
	public ModelAndView index(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		String path = PagePathUtil.index;
		try{
			
		}catch(Exception e){
			e.printStackTrace();
			LoggerUtil.getLogger().error("back_index_page"+e.getMessage(), e);
		}
		return new ModelAndView(path,modelMap);
	}
	
	/***
	 * @param account 
	 * 			用户账号
	 * @param password
	 * 			密码
	 * @param verifyCode 
	 * 			验证码
	 * @return JSONObject 
	 * 			状态信息
	 */
	@ResponseBody
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public JSONObject login(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value="account",required=true) String account,
			@RequestParam(value="password",required=true) String  password,
			@RequestParam(value="verifyCode",required=true) String  verifyCode){
		JSONObject json = new JSONObject();
		try{
			if( null == account || "".equals(account) 
				|| null == password || "".equals(password) 
				|| null == verifyCode || "".equals(verifyCode)){
				json.put("errorCode", ErrorCodeUtil.param_error_code);
				json.put("errorMsg", ErrorMsgUtil.param_error_msg);
				return json;
			}else{
				BackUserVo user = backUsersService.getUser(account);  
				if(null != user){
					String db_passwprd = user.getPassword();
					String salt = user.getSalt();
					boolean flag = PasswordUtil.validPassword(db_passwprd, password, salt);  //瀵嗙爜楠岃瘉
					if(flag){
						String code = (String)request.getSession().getAttribute("userA"+com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
						if(code.equals(verifyCode.toString())){
							user.setLastLoginDate(OtherUtils.getCurrentDate());
							backUsersService.saveUser(user);
							request.getSession().setAttribute("Back_user", user);
							json.put("success", "success");
							return json;
						}else{
							json.put("errorCode",ErrorCodeUtil.verify_error_code );
							json.put("errorMsg", ErrorMsgUtil.verify_code_msg);
							return json;
						}
					}else{
						json.put("errorCode", ErrorCodeUtil.password_error_code);
						json.put("errorMsg", ErrorMsgUtil.password_error_msg);
						return json;
					}
				}else{
					json.put("errorCode", ErrorCodeUtil.account_error_code);
					json.put("errorMsg", ErrorMsgUtil.account_error_msg);
					return json;
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			LoggerUtil.logger.error("back_login_post"+e.getMessage(),e);
		}
		return json;
	}
	/**
	 *  登出
	 * @param req
	 * @param resp
	 * @return
	 */
	@RequestMapping(value="logout")
	public String logout(HttpServletRequest req, HttpServletResponse resp) {
		req.getSession().removeAttribute("Back_user");
		return "login";
	}
	
}
